package com.example.springboot_demo.config;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
    Created with IntelliJ IDEA.
    @Author: 文
    @Date: 2024/12/5
    @Time: 10:57
    To change this template use File | Settings | File Templates.
    @Description: 
*/
public class WebSocketHandler extends TextWebSocketHandler {

    private final WebSocketService webSocketService;

    public WebSocketHandler(WebSocketService webSocketService) {
        this.webSocketService = webSocketService;
}

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 可根据需求处理收到的消息
        System.out.println("Received message: " + message.getPayload());
    }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        if (webSocketService != null) {
            System.out.println("WebSocket connected: " + session.getId());
            webSocketService.addSession(session);  // 添加连接的客户端
        } else {
            System.err.println("WebSocketService is not initialized.");
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        if (webSocketService != null) {
            System.out.println("WebSocket disconnected: " + session.getId());
            webSocketService.removeSession(session);  // 移除断开的客户端
        } else {
            System.err.println("WebSocketService is not initialized.");
        }
    }
}
